package com.template.ejb.datasource.bean;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.template.ejb.datasource.PersonDAO;
import com.template.ejb.domain.Person;

@Stateless
public class PersonDAOBean implements PersonDAO {

	@PersistenceContext(unitName = "Default")
	private EntityManager entityManager;

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/**
	 * 	
	 */
	@Override
	public void create(Person person) {
		person.setLastModified(new Date());
		person.setCreateDate(new Date());
		entityManager.persist(person);
	}

	/**
	 * 
	 */
	@Override
	public void delete(Person person) {
		entityManager.remove(person);
	}

	/**
	 * 
	 */
	@Override
	public Person update(Person person) {
		return (Person) entityManager.merge(person);
	}

	/**
	 * 
	 */
	@Override
	public Person findById(Long id) {
		Person person = entityManager.find(Person.class, id);
		if (person == null || person.getIsDeleted() == null
				|| person.getIsDeleted()) {
			return null;
		}
		return person;
	}

	/**
	 * 
	 */
	@Override
	public Person findByLogin(String login) {
		Person person = null;
		try {
			person = (Person) entityManager
					.createQuery(
							"select p from Person p where p.login=:login and p.isDeleted = false")
					.setParameter("login", login).getSingleResult();
		} catch (NoResultException e) {
			return null;
		} catch (NonUniqueResultException e) {
			return null;
		}
		return person;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person> getPersons(int offset, int limit) {

		Query q = entityManager.createQuery(
				"select p from Person p where p.isDeleted = false")
				.setFirstResult(offset).setMaxResults(limit);

		return q.getResultList();

	}
}
